/*
 * Licensed to the Apache Software Foundation (ASF) under one or more
 * contributor license agreements.  See the NOTICE file distributed with
 * this work for additional information regarding copyright ownership.
 * The ASF licenses this file to You under the Apache License, Version 2.0
 * (the "License"); you may not use this file except in compliance with
 * the License.  You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package com.zxm.dubbodemo.provider.service;

import com.alibaba.csp.sentinel.annotation.SentinelResource;
import com.alibaba.csp.sentinel.slots.block.BlockException;
import com.zxm.dubbodemo.api.DemoServiceFacade;
import com.zxm.dubbodemo.api.UserDto;
import org.apache.dubbo.config.annotation.Service;
import org.springframework.beans.factory.annotation.Value;

/**
 * Default {@link DemoServiceFacade}
 *
 * @see DemoServiceFacade
 * @since 2.7.0
 */
@Service(version = "${demo.service.version}")
public class DefaultDemoService implements DemoServiceFacade {

    @Value("${user.age}")
    private String serviceName;

    @SentinelResource(value = "sayHello", blockHandler = "exceptionHandler", fallback = "sayHelloFallback")
    @Override
    public UserDto sayHello(String name) {
        //        int i = 5/0;
        if ((int) (Math.random() * 10 + 1) > 5) {
            System.out.println("发生异常");
          throw new RuntimeException("发生异常");
        }
        UserDto ut = new UserDto();
        ut.setName("zxm");
        ut.setAge(19);
        return ut;
    }

    public UserDto sayHelloFallback(String name) {
        UserDto ut = new UserDto();
        ut.setName("default");
        ut.setAge(19);
        return ut;
    }
    // Block 异常处理函数，参数最后多一个 BlockException，其余与原函数一致.
    public UserDto exceptionHandler(String name, BlockException ex) {
        // Do some log here.
        //        ex.printStackTrace();
        System.out.println("当前系统较忙，请稍后再试！");
        UserDto ut = new UserDto();
        ut.setName("当前系统较忙，请稍后再试！");
        ut.setAge(19);
        return ut;
    }
}